#!/bin/bash
# 固定 WIFI IP 地址

# 请确保 WIFI 名称及密码正确
WIFI_NAME="MPI-Lab"
WIFI_PW="MPILab@SJTU"

echo ">>> Please connect to wifi first."
dev=$( ip route | perl -n -e '/dev (.*) proto dhcp/ && print $1')
ip=$( ip route | perl -n -e '/src (.*) metric/ && print $1')
router=$( ip route | perl -n -e '/via (.*) dev/ && print $1')
echo "Dev: ${dev}"
echo "IP: ${ip}"
echo "Router: ${router}"

# 将当前 ip 写入 /etc/netplan/01-network-manager-all.yaml, 固定静态 ip
echo ">>> 将当前 ip 写入 /etc/netplan/01-network-manager-all.yaml, 并重启 wifi "
net_type=$([[ ${dev} =~ wlan.* ]] && echo "wifis" || echo "ethernets")
cat <<EOF | sudo tee -a /etc/netplan/01-network-manager-all.yaml >/dev/null
  ${net_type}:
    ${dev}:
      dhcp4: no
      addresses: [${ip}/24]
      optional: true
      gateway4: ${router}
      nameservers:
        addresses: [114.114.114.114, 8.8.8.8]
EOF
if [[ $net_type == "wifis" ]]; then
  cat <<EOF | sudo tee -a /etc/netplan/01-network-manager-all.yaml >/dev/null
      access-points:
        "${WIFI_NAME}":  # wifi 名称
          password: "${WIFI_PW}"  # wifi 密码
EOF
fi

sudo netplan generate # 没有报错则ok
sudo netplan apply # 此时应用静态ip修改，IP地址发生改变